package FileTree;

import java.util.ArrayList;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.tree.TreeModel;
import javax.swing.tree.TreePath;

/**
 *
 * @author popperik
 */
public class FileTreeModel implements TreeModel {
    
    FileWrap root;
    ArrayList<TreeModelListener> listeners;
    
    // Static methods
    
    public static ArrayList<FileWrap> getAvailableRoots() {
        return FileWrap.getAvailableRoots();
    }
    
    // Constructors
    
    public FileTreeModel() {
        root = null;
        listeners = new ArrayList<>();
    }
    
    // Member functions
    
    @Override
    public void addTreeModelListener(TreeModelListener l) {
        listeners.add(l);
    }
    
    @Override
    public Object getChild(Object parent, int index) {
        return ((FileWrap) parent).getChildAt(index);
    }
    
    public ArrayList<FileWrap> getChildren(Object parent) {
        return ((FileWrap) parent).getChildren();
    }
    
    @Override
    public int getChildCount(Object parent) {
        return ((FileWrap) parent).getChildCount();
    }
    
    @Override
    public int getIndexOfChild(Object parent, Object child) {
        return ((FileWrap) parent).findChild((FileWrap) child);
    }
        
    @Override
    public Object getRoot() {
        return root;
    }

    @Override
    public boolean isLeaf(Object node) {
        return ((FileWrap) node).isFile();
    }
    
    @Override
    public void removeTreeModelListener(TreeModelListener l) {
        listeners.remove(l);
    }
    
    public void setRoot(Object root) {
        this.root = (FileWrap) root;
        TreeModelEvent e = new TreeModelEvent(root, new Object[] { root });
        for(TreeModelListener listener : listeners) {
            listener.treeStructureChanged(e);
        }
    }

    @Override
    public void valueForPathChanged(TreePath path, Object newValue) {
        throw new UnsupportedOperationException("Renaming is not supported");
    }    
}
